<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body {
            font-family:Arial,sans-serif;margin:20px;
        }
        #chat-box{
            border:1px solid #ccc;
            padding:10px;
            height: 300px;
            overflow-y: auto;
            margin-bottom:10px;
        }
        .msg {
            margin:4px;
        }
        .msg.me {
            text-align:right;
            color: blue;
        }
        .msg.other { text-align:left;
                     color:green;
                 }
        input,button {
            margin:5px;padding: 5px;
        }
    </style>
</head>
<body>
<h2>WebSocket聊天测试</h2>
<div id="status">连接中...</div>
<div id="chat-box"></div>
<form id="chat-form"onsubmit="sendMessage();return false;">
    <div><label>房间名：</Label><input type="text" id="room" value="room1"></div>
    <div><Label>目标用户ID（可选）：</Label><input type="text"id="to"pLacehoLder="填则私聊，不填则群聊"></div>
    <div><Label>消息内容：</Label><input type="text"id="message"placeholder="输入消息..." style="width: 250px;"><button type="submit">发送</button> </div>
</form>
<script>
    const token="user3";//实际应为 JWT
    const wsUrl=`ws://localhost:8080/ws?token=${token}`;
    let ws;
    let reconnectAttempts =0;
    const chatBox =document.getElementById('chat-box');
    const statusDiv = document.getElementById('status');
    function connect()  {

        ws = new WebSocket(wsUrl);
        ws.onopen =()=>{
            statusDiv.textContent ='已连接';
            reconnectAttempts =0;
            //自动加入房间
            ws.send(JSON.stringify({type:'join',room:room.value}));
        };
        ws.onmessage = (evt) => {
            const msg = JSON.parse(evt.data);
            console.log('receive,msg:',msg);
            if (msg.type ==='message'){
                renderMessage(msg.from || '对话',msg.payload);
                if (msg.id){
                    ws.send(JSON.stringify({type:'ack',id:msg.id,from: token,time:Date.now()}));
                }
            }
        };
        ws.onerror =(err)=>{
            console.error('WebSocket错误:',err);
            ws.close()
        };
        ws.onclose =()=>{
            statusDiv.textContent ='已断开';
            reconnectAttempts++;
            if (reconnectAttempts <3){
                setTimeout(connect,2000);
            }
        };
    }
    function  sendMessage(){
        const roomInput = document.getElementById('room');
        const toInput = document.getElementById('to');
        const messageInput = document.getElementById('message');
        const room = roomInput.value || 'room1';
        const to = toInput.value || '';
        const text = messageInput.value.trim();
        if (!text){
            return;
        }
        const msg ={
            type:"message",
            id:"msg-"+Date.now(),
            room:room,
            from: token,
            payload: text,
            seq:Date.now(),
            time: Date.now()
        };
        if (to.trim()) {
            msg.to = to.trim();
        }
        ws.send(JSON.stringify(msg));
        renderMessage('我', text, true)
        messageInput.value ='';
    }
    function renderMessage(from,payload, isMe){
        const msgDiv = document.createElement('div');
        msgDiv.className =`msg ${isMe ? 'me' : 'other'}`;
        msgDiv.textContent =`${from}:${payload}`;
        chatBox.appendChild(msgDiv);
        chatBox.scrollTop = chatBox.scrollHeight;
    }
    connect()
    room.onchange = () => {
        ws.send(JSON.stringify({type:'join',room:room.value}));
    }
</script>
</body>
</html>